package com.gz.furnitures.web;

import com.google.gson.Gson;
import com.gz.furnitures.entity.Cart;
import com.gz.furnitures.entity.CartItem;
import com.gz.furnitures.entity.Furn;
import com.gz.furnitures.entity.Page;
import com.gz.furnitures.service.impl.FurnServiceImpl;
import com.gz.furnitures.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/cartServlet")
public class CartServlet extends BasicServlet{
    FurnServiceImpl furnService=new FurnServiceImpl();

    protected void addItemByAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        CartItem item = new CartItem(furn.getId(), furn.getName(), furn.getPrice(), 1, furn.getPrice());
        //获得购物车，没有则创建
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        Map <String,Object> resultMap = new HashMap<>();
        if (cart == null) {
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }
        //这里是boolean值，我在方法中做了修改，如果库存不足则不做修改直接返回false
        //因为这个是ajax方法，不管addItem返回false还是true都直接返回json值，故这里不用在判断了
        cart.addItem(item);

        //添加完毕后，返回json数据给前端
        //前端得到数据后，进行局部刷新即可
        // 与没用ajax的区别相比，没用ajax是返回整个页面，造成数据传输量大
        // 而用ajax只需返回json数据进行局部刷新
        resultMap.put("cartTotalCount", cart.getTotalCount());
        String resultJson = new Gson().toJson(resultMap);
        response.getWriter().write(resultJson);

    }

    //添加家具数据到购物车
    protected void addItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        CartItem item = new CartItem(furn.getId(), furn.getName(), furn.getPrice(), 1, furn.getPrice());
        //获得购物车，没有则创建
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
        }
        if(!cart.addItem(item)){
            System.out.println("添加失败");
            String referer = request.getHeader("Referer");
            response.sendRedirect(referer);
            return;
        }
        //修改完后添加到session中(持久化)
        request.getSession().setAttribute("cart", cart);
        //上一个页面的地址，即发送地址
        String referer = request.getHeader("Referer");
        //回到原来地址
        response.sendRedirect(referer);
    }

    protected void cartPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        Page<CartItem> cartPage =new Page<>();
        if (cart != null) {
            cartPage = cart.getCartPage(pageNo, pageSize);
        }else {
            cart = new Cart();
        }
        request.getSession().setAttribute("cart", cart);
        StringBuilder url = new StringBuilder("cartServlet?action=cartPage");
        cartPage.setUrl(url.toString());
        request.getSession().setAttribute("cartPage", cartPage);
        request.getRequestDispatcher("/views/cart/cart.jsp").forward(request, response);
    }

    protected void updateCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"), 0);
        //这里可以根据业务来处理
        int count = DataUtils.parseInt(request.getParameter("count"), 1);

        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.updateCount(id,count);
            request.getSession().setAttribute("cart", cart);
        }
        //返回修改之前的页面
        response.sendRedirect(request.getHeader("Referer"));
    }

    protected void deleteItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"), 0);
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.deleteItem(id);
            request.getSession().setAttribute("cart", cart);
        }
        //如果删除的是这一页的最后一个，那么返回原来页的上一页
        if (cart.getItemType()%pageSize==0&&cart.getItemType()>0) {
            response.sendRedirect(request.getContextPath()+"/cartServlet?action=cartPage&pageNo="+(pageNo-1));
        }else{
            //返回修改之前的页面
            response.sendRedirect(request.getHeader("Referer"));
        }
    }

    protected void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if (cart != null) {
            cart.clear();
            request.getSession().setAttribute("cart", cart);
            response.sendRedirect(request.getContextPath()+"/cartServlet?action=cartPage&pageNo=1");
        }

    }
}
